<template>
  <div style="text-align: end; margin: 15px 30px 0px 0px">
    <div v-if="!isLogin">
      <ElButton
        @click="router.push('/user02')"
        type="primary"
        size="large"
        round
        ><el-icon><User /></el-icon>请先登录</ElButton
      >
    </div>

    <div v-if="isLogin">
      <div>
        <ElDropdown @command="handleMenu" v-loading="loading">
          <div style="display: flex">
            <div>
              <ElAvatar :size="50" :src="user.data.exinfo.logo"> </ElAvatar>
            </div>
            <div style="margin-top: 18px">
              <!-- <el-icon size="20">
                <arrow-down />
              </el-icon> -->
            </div>
          </div>

          <template #dropdown>
            <ElDropdownMenu class="i">
              <ElDropdownItem
                ><el-icon><Avatar /></el-icon>
                {{ user.data.userInfo.nickname }}({{ user.data.user.username }})
              </ElDropdownItem>

              <ElDropdownItem divided @click="router.push('/')"
                ><el-icon><House /></el-icon> 用户主页
              </ElDropdownItem>

              <ElDropdownItem divided @click="router.push('/soul')"
                ><el-icon><ChatSquare /></el-icon> 留言板
              </ElDropdownItem>

              <ElDropdownItem @click="router.push(`/user/test/-1`)"
                ><el-icon><ChatLineRound /></el-icon>我的消息
              </ElDropdownItem>

              <ElDropdownItem divided command="pwd"
                ><el-icon><Unlock /></el-icon> 修改密码
              </ElDropdownItem>
              <ElDropdownItem @click="showinfo(user.data.userInfo)"
                ><el-icon><Notebook /></el-icon> 修改用户信息
              </ElDropdownItem>
              <ElDropdownItem command="logo"
                ><el-icon><Notebook /></el-icon> 修改用户头像
              </ElDropdownItem>

              <ElDropdownItem
                divided
                command="follow"
                @click="queryfollow(user.data.user.uid)"
                ><el-icon size="18"><StarFilled /></el-icon> 我的关注({{
                  user.data.exinfo.mineFollows
                }})</ElDropdownItem
              >
              <ElDropdownItem
                command="followed"
                @click="queryfollowed(user.data.user.uid)"
                ><el-icon><Star /></el-icon> 我的粉丝({{
                  user.data.exinfo.followMines
                }})
              </ElDropdownItem>

              <ElDropdownItem divided command="logout"
                ><el-icon><SwitchButton /></el-icon> 安全退出
              </ElDropdownItem>
            </ElDropdownMenu>
          </template>
        </ElDropdown>
      </div>

  
    </div>
  </div>

  <!-- <ElDivider>
    <el-icon><star-filled /></el-icon>
  </ElDivider> -->

  <!-- 关注的对话框 -->
  <div>
    <ElDialog
      v-model="dfollow"
      title="我的关注"
      width="40%"
      @close="shuaxin"
      :close-on-click-modal="false"
    >
      <div v-for="i in followlist">
        <ElForm :inline="true" style="display: flex">
          <ElFormItem>
            <ElAvatar :size="50" :src="i.exinfo.logo"></ElAvatar>
          </ElFormItem>

          <ElFormItem>
            <div>{{ i.userInfo.nickname }}({{ i.user.username }})</div>
          </ElFormItem>

          <div
            style="display: flex; justify-content: end; width: 100%"
            v-loading="loading"
          >
            <ElFormItem>
              <ElButton type="danger" v-if="!i.exinfo.mineFollow"
                >关注</ElButton
              >
              <ElButton
                v-if="i.exinfo.mineFollow && !i.exinfo.followMine"
                @click="follow(i.user.uid)"
                >已关注</ElButton
              >
              <ElButton v-if="i.exinfo.mineFollow && i.exinfo.followMine"
                >互相关注</ElButton
              >
              <ElButton type="info">私信</ElButton>
            </ElFormItem>
          </div>
        </ElForm>
      </div>
    </ElDialog>
  </div>

  <!-- 粉丝的对话框 -->
  <div>
    <ElDialog
      v-model="dfollowed"
      title="我的粉丝"
      width="40%"
      @close="shuaxin"
      :close-on-click-modal="false"
    >
      <div v-for="i in followedlist">
        <ElForm :inline="true" style="display: flex">
          <ElFormItem>
            <ElAvatar :size="50" :src="i.exinfo.logo"></ElAvatar>
          </ElFormItem>

          <ElFormItem>
            <div>{{ i.userInfo.nickname }}({{ i.user.username }})</div>
          </ElFormItem>

          <div
            style="display: flex; justify-content: end; width: 100%"
            v-loading="loading"
          >
            <ElFormItem>
              <ElButton
                type="danger"
                v-if="!i.exinfo.mineFollow"
                @click="follow(i.user.uid)"
                >关注</ElButton
              >
              <ElButton
                v-if="i.exinfo.mineFollow && !i.exinfo.followMine"
                @click="follow(i.user.uid)"
                >已关注</ElButton
              >
              <ElButton
                v-if="i.exinfo.mineFollow && i.exinfo.followMine"
                @click="follow(i.user.uid)"
                >互相关注</ElButton
              >
              <ElButton type="info" @click="openChat">私信</ElButton>
            </ElFormItem>
          </div>
        </ElForm>
      </div>
    </ElDialog>
  </div>

  <!-- 修改密码的对话框 -->
  <div>
    <ElDialog
      v-model="dpassword"
      title="修改密码"
      :close-on-click-modal="false"
      width="32%"
    >
      <ElForm>
        <ElFormItem>
          <ElInput
            size="large"
            v-model="password.oldPwd"
            placeholder="请输入旧密码"
            :show-password="true"
          />
        </ElFormItem>
        <ElFormItem>
          <ElInput
            size="large"
            v-model="password.newPwd01"
            placeholder="请输入新密码"
            :show-password="true"
          />
        </ElFormItem>
        <ElFormItem>
          <ElInput
            size="large"
            v-model="password.newPwd02"
            placeholder="请再次输入新密码"
            :show-password="true"
          />
        </ElFormItem>
        <div style="text-align: end; display: flex; justify-content: end">
          <ElFormItem>
            <ElButton @click="dpassword = false" type="danger"
              ><el-icon><CloseBold /></el-icon>关闭</ElButton
            >
            <ElButton @click="updatepwd" type="success"
              ><el-icon><Select /></el-icon>确认</ElButton
            >
          </ElFormItem>
        </div>
      </ElForm>
    </ElDialog>
  </div>

  <!-- 修改用户信息的对话框 -->
  <div>
    <ElDialog
      v-model="duserinfo"
      title="修改用户信息"
      :close-on-click-modal="false"
      width="50%"
    >
      <ElForm :model="form" label-width="auto" style="max-width: 600px">
        <ElFormItem label="用户名">
          <ElInput size="large" v-model="userinfo.nickname" />
        </ElFormItem>
        <ElFormItem label="QQ">
          <ElInput size="large" v-model="userinfo.qq" />
        </ElFormItem>
        <ElFormItem label="微信">
          <ElInput size="large" v-model="userinfo.wechat" />
        </ElFormItem>

        <ElFormItem label="性别">
          <ElRadioGroup v-model="userinfo.sex">
            <ElRadio label="男" value="f"></ElRadio>
            <ElRadio label="女" value="m"></ElRadio>
            <ElRadio label="保密" value="n"></ElRadio>
          </ElRadioGroup>
        </ElFormItem>

        <ElFormItem label="个人介绍">
          <ElInput size="large" v-model="userinfo.info" type="textarea" />
        </ElFormItem>

        <div style="text-align: end; display: flex; justify-content: end">
          <ElFormItem>
            <ElButton @click="duserinfo = false" type="danger"
              ><el-icon><CloseBold /></el-icon>关闭</ElButton
            >
            <ElButton type="success" @click="updateinfo"
              ><el-icon><Select /></el-icon>修改</ElButton
            >
          </ElFormItem>
        </div>
      </ElForm>
    </ElDialog>
  </div>

  <!-- 私信的对话框 -->
  <div class="chat-container">
   
    <!-- 聊天对话框 -->
    <el-dialog  title="私信" v-model="chatDialogVisible" :close-on-click-modal="false" class="chat-dialog">
      <!-- 消息显示区域 -->
      <div class="chat-messages" ref="chatMessages">
        <!-- 循环渲染每条消息 -->
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.sender === 'user' ? 'user-message' : 'friend-message']">
          <div class="message-content">{{ message.content }}</div>
        </div>
      </div>
      <!-- 输入框和发送按钮 -->
      <div class="chat-input-container">
        <el-input v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage" class="chat-input"></el-input>
        <el-button type="primary" @click="sendMessage" class="send-button">发送</el-button>
      </div>
    </el-dialog>
  </div>


  <!-- 用户修改头像对话框 -->
  <div>
    <ElDialog
      title="修改头像"
      v-model="logoDialog"
      :close-on-click-modal="false"
      class="avatar-dialog"
    >
      <div class="avatar-upload-container">
        <label for="avatar-input" class="avatar-upload-label">
          <img
            v-if="previewImage"
            :src="previewImage"
            alt="预览头像"
            class="avatar-preview"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </label>
        <input
          id="avatar-input"
          type="file"
          accept="image/*"
          @change="handleFileChange"
          class="avatar-input"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <ElButton @click="logoDialog = false">取消</ElButton>
          <ElButton type="primary" @click="updatalogo">确定</ElButton>
        </span>
      </template>
    </ElDialog>
  </div>
</template>

<script setup>
import {
  ElAvatar,
  ElButton,
  ElDialog,
  ElDivider,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElUpload,
} from 'element-plus';
import userstore from '../store/user';
import { useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { onMounted, ref } from 'vue';
import Api from '../script/Api';

const { getLoginInfo } = userstore();
const { user, isLogin } = storeToRefs(userstore());






const router = useRouter();
//#region 菜单处理
const handleMenu = (command) => {
  console.log('菜单', command);
  if (command == 'logout') {
    logout();
  } else if (command == 'follow') {
  
    dfollow.value = true;
    
  } else if (command == 'followed') {
    dfollowed.value = true;
  } else if (command == 'pwd') {
    dpassword.value = true;
  } else if (command == 'logo') {
    logoDialog.value = true;
  }
};


//#endregion

//#region 私信相关参数


// 控制对话框的显示与隐藏
const chatDialogVisible = ref(false);

// 绑定输入框的值
const newMessage = ref('');

// 存储消息列表
const messages = ref([
  { sender: 'friend', content: '你好！有什么可以帮你的吗？' }
]);

// 打开聊天对话框的方法
const openChat = () => {
  chatDialogVisible.value = true;
};

// 发送消息的方法
const sendMessage = () => {
  if (newMessage.value.trim()) { // 检查输入框是否为空
    messages.value.push({ sender: 'user', content: newMessage.value }); // 将用户消息添加到消息列表
    newMessage.value = ''; // 清空输入框
    scrollToBottom(); // 滚动到底部
    handleFriendResponse(); // 模拟朋友回复
  }
};

// 模拟朋友回复的方法
const handleFriendResponse = () => {
  setTimeout(() => {
    messages.value.push({ sender: 'friend', content: '这是朋友的回复。' }); // 添加朋友的消息
    scrollToBottom(); // 滚动到底部
  }, 1000); // 模拟延迟1秒后回复
};

// 滚动到底部的方法
const scrollToBottom = () => {
  const chatMessages = document.querySelector('.chat-messages'); // 获取消息显示区域的DOM元素
  if (chatMessages) {
    chatMessages.scrollTop = chatMessages.scrollHeight; // 滚动到底部
  }
};

// 页面加载完成后执行的初始化操作
onMounted(() => {
  // 可以在这里进行一些初始化操作
});




//#endregion


//#region 修改用户头像
const files = ref(null);
const logoDialog = ref(false);
const previewImage = ref(null);

// 处理文件选择的事件
// const handleFileChange = (e) => {
//   files.value = e.target.files[0];
//   console.log('文件', files.value);
// };

const handleFileChange = (e) => {
  files.value = e.target.files[0];
  // 预览图片
  const reader = new FileReader();
  reader.onload = (event) => {
    previewImage.value = event.target.result;
  };
  reader.readAsDataURL(files.value);
};

const updatalogo = () => {
  Api.upload('/files', files.value, {}, (data) => {
    if (data.success) {
      console.log('data', data.data);
      logo(Api.logo(data.data.id));
    } else {
      ElMessage.error(data.message);
    }
  });
};

const logo = (info) => {
  Api.post('/user/updatelogo', { logo: info }, (data) => {
    if (data.success) {
      ElMessage.success(data.message);
      shuaxin();
    } else {
      ElMessage.error(data.message);
    }
  });
};

//#endregion

//#region 修改密码操作
const dpassword = ref(false);
const password = ref({
  oldPwd: '',
  newPwd01: '',
  newPwd02: '',
});

const updatepwd = () => {
  Api.post('/user/updatePwd', password.value, (data) => {
    if (data.success) {
      password.value = {};
      ElMessage.success(data.message);
      dpassword.value = false;
    } else {
      ElMessage.error(data.message);
    }
  });
};

//#endregion

//用户安全退出操作
const logout = () => {
  Api.post('/user/logout', {}, (data) => {
    if (data.success) {
      ElMessage.success(data.message);
      isLogin.value = false;
      shuaxin();
    } else {
      ElMessage.error(data.message);
    }
  });
};
//刷新页面
const shuaxin = () => {
  location.reload();
};

const page = ref({
  pageNum: 1,
  pageSize: 10,
});

//查询用户关注列表操作
const followlist = ref([]);
const dfollow = ref(false);
const loading = ref(false);
const id = ref([]);
const queryfollow = (uid) => {
  loading.value = true;
  Api.get(
    `/user/queryfollow/${uid}/${page.value.pageNum}/${page.value.pageSize}`,
    {},
    (data) => {
      if (data.success) {
        ElMessage.success('');
        followlist.value = data.data;
        page.value = data.pageBean;
        loading.value = false;
        id.value = uid;
      } else {
        loading.value = false;
        ElMessage.error(data.message);
      }
    }
  );
};

//#region 查询用户粉丝列表
const followedlist = ref([]);
const dfollowed = ref(false);

const queryfollowed = (uid) => {
  loading.value = true;
  Api.get(
    `/user/queryfollowed/${uid}/${page.value.pageNum}/${page.value.pageSize}`,
    {},
    (data) => {
      if (data.success) {
        followedlist.value = data.data;
        loading.value = false;
        id.value = uid;
      } else {
        loading.value = false;
        ElMessage.error(data.message);
      }
    }
  );
};

//#endregion

//#region 用户关注操作
const follow = (uid) => {
  loading.value = true;
  Api.get(`/user/follow/${uid}`, {}, (data) => {
    if (data.success) {
      ElMessage.success('关注成功');
      queryfollow(id.value);
      queryfollowed(id.value);
      loading.value = false;
    } else {
      ElMessage.error(data.message);
      loading.value = false;
    }
  });
};

//#endregion

//#region 用户修改用户信息的对话框
const duserinfo = ref(false);
const userinfo = ref({
  nickname: '',
  sex: 'n',
  wechat: '',
  qq: '',
  info: '',
});

const showinfo = (info) => {
  duserinfo.value = true;
  userinfo.value = info;
  console.log('info', info);
};

const updateinfo = () => {
  Api.post('/user/updateInfo', userinfo.value, (data) => {
    console.log('data', data);
    if (data.success) {
      ElMessage.success(data.message);
      duserinfo.value = false;
    } else {
      ElMessage.error(data.message);
    }
  });
};

//#endregion
</script>

<style scoped>
.avatar-dialog {
  width: 400px;
}

.avatar-upload-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-upload-label {
  width: 150px;
  height: 150px;
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}

.avatar-upload-label:hover {
  border-color: #409eff;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar-input {
  display: none;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
}

.el-button {
  margin: 0 10px;
}



/* 私信的样式 */

/* 聊天容器 */
.chat-container {
  text-align: center;
}

/* 对话框样式 */
.chat-dialog {
  width: 600px;
}

/* 消息显示区域样式 */
.chat-messages {
  max-height: 400px; /* 最大高度 */
  overflow-y: auto; /* 启用垂直滚动条 */
  padding: 10px; /* 内边距 */
  border-bottom: 1px solid #e4e7ed; /* 底部边框 */
  display: flex; /* 使用Flexbox布局 */
  flex-direction: column; /* 垂直排列消息 */
}

/* 每条消息的基本样式 */
.message {
  margin: 10px 0; /* 上下外边距 */
  padding: 10px; /* 内边距 */
  border-radius: 5px; /* 圆角 */
  max-width: 70%; /* 最大宽度 */
  word-wrap: break-word; /* 自动换行 */
}

/* 用户发送的消息样式 */
.user-message {
  background-color: #e6f7ff; /* 背景颜色 */
  align-self: flex-end; /* 右对齐 */
}

/* 朋友发送的消息样式 */
.friend-message {
  background-color: #f0f9eb; /* 背景颜色 */
  align-self: flex-start; /* 左对齐 */
}

/* 输入框和发送按钮容器 */
.chat-input-container {
  display: flex; /* 使用Flexbox布局 */
  align-items: center; /* 垂直居中对齐 */
  padding: 10px; /* 内边距 */
}

/* 输入框样式 */
.chat-input {
  flex: 1; /* 占据剩余空间 */
  margin-right: 10px; /* 右边距 */
}

/* 发送按钮样式 */
.send-button {
  min-width: 80px; /* 最小宽度 */
}

.i{
  animation: 2.5s cubic-bezier(.25, 1, .30, 1) circle-in-center both;
}


@keyframes circle-in-center {
  from {
    clip-path: circle(0%);
  }
  to {
    clip-path: circle(125%);
  }
}





</style>
